package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.springframework.util.ResourceUtils;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description TODO(这里用一句话描述这个类的作用)
 *
 * @author liuqinghua
 * @date 2025-4-2
 */
@Slf4j
public class ItextPdfSyUtils {

    public static void addSy(String content, String outPath, String inputPath) {
        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            File file = ResourceUtils.getFile(inputPath);
            File fontFile = ResourceUtils.getFile("font/simfang.ttf");
            InputStream inputStream = new FileInputStream(file);
            // 读取原始 PDF 文件F
            reader = new PdfReader(inputStream);
            stamper = new PdfStamper(reader, new FileOutputStream(outPath));
            // 获取 PDF 中的页数
            int pageCount = reader.getNumberOfPages();
            // 添加水印
            for (int i = 1; i <= pageCount; i++) {
                PdfContentByte contentByte = stamper.getUnderContent(i);
                contentByte.beginText();
                // 设置中文字体
                contentByte.setFontAndSize(
                        BaseFont.createFont(fontFile.getAbsolutePath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED),
                        36f);
                // 设置样式
                contentByte.setColorFill(BaseColor.LIGHT_GRAY);
                contentByte.showTextAligned(Element.ALIGN_CENTER, content, 200, 200, 45);
                contentByte.endText();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("pdf 添加水印出错:", e);
        } finally {
            try {
                if (stamper != null) {
                    stamper.close();
                }

            } catch (Exception e) {
            }
            try {
                if (reader != null) {
                    reader.close();
                }
                reader.close();
            } catch (Exception e) {
            }
        }
    }

    public static void main(String[] args) {
        ItextPdfSyUtils.addSy("张三-1234", "D:/opt/jsps/tmp/form/罗教师2.pdf", "D:/opt/jsps/tmp/form/罗教师1.pdf");
    }

}
